import axios from "axios";

interface Result<T> {
  success: boolean;
  message: string;
  data: T;
}

// baseURL设置/超时时间设置
const instance = axios.create({
  baseURL: "http://127.0.0.1:8083", // 配置请求基地址
  timeout: 5000, // 配置等待时间
});

// 添加请求拦截器
instance.interceptors.request.use(
  function (config) {
    // 操作请求
    return config;
  },
  function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);

// 添加响应拦截器
instance.interceptors.response.use(
  function (response) {
    // 操作响应
    return response.data;
  },
  function (error) {
    // 对响应错误做点什么
    return Promise.reject(error);
  }
);

/**
 * @param {String} - url  请求地址
 * @param {String} - method  请求类型
 * @param {Object} - submitData  对象类型，提交数据
 */
export const request = async <T>(
  url: any,
  method: any,
  submitData?: any
): Promise<Result<T>> => {
  try {
    const response = await instance({
      url,
      method,
      [method.toLowerCase() === "get" ? "params" : "data"]: submitData,
    });

    return response as any;
  } catch (error: any) {
    return {
      success: false,
      message: error.message || "请求失败",
      data: null as any,
    };
  }
};

/**
 * @param {String} - url  请求地址
 * @param {Object} - params  路径参数对象
 */

// 这种方法传递到后端，匹配不到，java待优化
export const requestWithParams = async <T>(
  url: string,
  params: { [key: string]: any }
): Promise<Result<T>> => {
  // 替换路径参数
  Object.keys(params).forEach((key) => {
    url = url.replace(`{${key}}`, params[key]);
  });

  return request<T>(url, "get");
};

interface UploadResponse {
  message: string;
}
// 文件上传接口
export const uploadExcelFile = async <T>(
  file: File,
  mode: string = "files"
): Promise<Result<T>> => {
  const formData = new FormData();
  formData.append("file", file);

  const response = await request<Result<T>>(
    `/${mode}/upload`,
    "POST",
    formData
  );
  return response.data;
};